</html>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>明德人才管理系统</title>
  <link rel="stylesheet" href="/layui-v2.6.8/layui/css/layui.css">
  <style>
    .c-gray {
      color: #ccc;
    }

    .c-green {
      color: green;
    }

    .c-red {
      color: red;
    }

    .box {
      display: flex;
      justify-content: center;
    }
  </style>
</head>

<body>
  <div class="layui-layout layui-layout-admin">
    <!-- 头部 -->
    {{include'./Public_documents/header.html'}}

    <!-- 左侧 -->
    {{include'./Public_documents/Left_menu.html'}}

    <div class="layui-body">
      <!-- 内容主体区域 -->
      <div class="box">

        
      </div>
     
      <!-- <div style="text-align:center;padding:30px;"> -->
      <div style="padding:30px;">
        <div>
          
          <input id="title" class="input-b" placeholder="输入你想要的搜索内容">
          <button type="button" class="layui-btn layui-btn-primary layui-btn-radius" id="btn">搜索</button>
          <!-- style="width: 200px; display:inline-block;  -->
            </div>
        <div style="padding: 15px;">
          <!-- <span class="layui-breadcrumb" lay-separator="/"></span>
            <a href="/">首页</a>
            <a href="/article">文章列表</a> -->
          <!-- 表格内容 -->
          <table align="center" width="1200px" border="1px" rules="all" class="layui-table" lay-skin="line">
            <tr>
              <td>序号</td>
              <td>标题</td>
              <td>所属分类</td>
              <td>图片</td>
              <td>作者</td>
              <td>内容</td>
              <td>审核状态</td>
              <td>添加时间</td>
              <td>修改时间</td>
              <td>操作时间</td>
            </tr>
            <tbody id="tbody"></tbody>
          </table>
          {{include'./Public_documents/bottom.html'}}
        </div>
        <div id="paging"></div>
      </div>

    </div>

  </div>
  <script src="https://momentjs.bootcss.com/downloads/moment.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="/layui-v2.6.8/layui/layui.js"></script>

  <script>
    // 初始化分页
    let curr = 1;
    let limit = 3;
    let title ; //搜索关键字
    let Audit_status;  //状态
    let isSearch = false;
    var laypage;
    let statusTextMap = {
      0: '<span class="layui-bg-orange">待审核</span>',
      1: '<span class="layui-bg-green">审核通过</span>',
      2: '<span class="layui-bg-black">审核失败</span>'
    }
    // 获取分页数据
    function GetPagingData(curr, limit, callback,where={}) {
      let params =Object.assign({curr,limit},where)
      $.get('/paging', params, function (res) {
          callback && callback(res)
      }, 'json');
    }
 //表格数据拼接
    function RenderingTableData(data) {
      let tbodyHtml = '';
      data.forEach((item, index) => {
        index = index + 1;
        let {
          id,
          title,
          name,
          img,
          author,
          content,
          Audit_status,
          add_time,
          Update_time
        } = item;
        add_time = moment.unix(add_time).format('YYY-MM-DD')
        Update_time = moment.unix(Update_time).format('YYY-MM-DD')
        let copyItem = JSON.stringify(item);
        tbodyHtml += ` <tr>
              <td>${index}</td>
              <td>${title}</td>
              <td>${name}</td>
              <td><img src="/${img}" width="100px"></td>
              <td>${author}</td>
              <td><button class="layui-btn layui-btn-sm showContent" data-item="${content}">查看全文</button></td>

              <td>${statusTextMap[Audit_status] }</td>
              <td>${add_time}</td>
              <td>${Update_time}</td>
              <td>
                <a href="/edit?id=${id}"
                  class="layui-btn layui-btn-xs layui-btn layui-btn-radius layui-btn-normal">编辑<i
                    class="layui-icon">&#xe642;</i></a>

                <a href="/delete?id=${id}"
                  class="layui-btn layui-btn-xs layui-btn layui-btn-radius layui-btn-danger"
                  onclick=' confirmDelete(" 确认删除吗？")'>删除<i class="layui-icon">&#xe640;</i></a>


                <a href="/recycle?id=${id}"
                  class="layui-btn layui-btn-xs layui-btn layui-btn-radius layui-btn-warm"
                  onclick='return confirm("加入回收站")'>加入回收站</a>
                <a href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn layui-btn-radius layui-btn-danger"
                  onclick=' ajaxDelete(this,"${id}","${img}")("确认删除吗？")'>ajax删除<i
                    class="layui-icon">&#xe640;</i></a>
              </td>
            </tr>`
      })
      return tbodyHtml;
    }

    // // 渲染分页结构
    function RenderPagingStructure(laypage, ele, count, limit) {
      //执行
      laypage.render({
        elem: ele,
        count,
        limit,
        jump: function (obj, first) {
          //第一次触发为true ，后面是undefin
          let {curr,limit} = obj;
           // 如果是搜索，则取消默认请求
          if(isSearch){ return;}
          GetPagingData(curr, limit, (res) => {
             // 获取分页数据
            //  console.log(res)
            let tbody = RenderingTableData(res.data)
            $('#tbody').html(tbody);
          },{title,Audit_status})
        }
      });
    }


    layui.use('laypage', function () {
      laypage = layui.laypage;

      //请求完毕之后，在渲染分页
      // 加载分页数据和总记录数
      GetPagingData(curr,limit,res=>{
        let {count,data} = res;
        // 渲染分页结构
        RenderPagingStructure(laypage,'paging',count,limit)
      })

    });


    //普通删除
    function confirmDelete(id, img) {
      layer.confirm('确认删除吗', {
        btn: ['是的', '取消'], //按钮
        shadeClose: true,
        shade: [0.3, '#000']
      }, () => {
        //点了是的按钮触发
        location.href = "/delete?id=" + id + "&img=" + img
      }, () => {
        layer.msg('你取消')
      });
    }

    //ajax异步删除
    function ajaxDelete(ele, id, img) {
      layer.confirm('确认删除吗', {
        btn: ['是的', '取消'],
        shadeClose: true,
        shade: [0.3, '#000']
      }, () => {
        //点了是的按钮触发
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (this.readyState === 4 && this.status === 200) {
            let data = JSON.parse(this.responseText); //接收数据
            let {
              code,
              message
            } = data;
            if (code === 20000) {
              $(ele).parents("tr").remove() //parent()方法从指定类型的直接父节点开始查找。parent()返回一个元素节点。
              setTimeout(function () {
                layer.msg('删除成功', {
                  icon: 1
                })
              }, 500)
              layer.closeAll();
            } else if (code === 30004) {
              layer.msg(message)
              location.href = "/login"
            } else {
              layer.msg("删除失败")
            }
          }

        }
        xhr.open("post", "/ajaxdelete", true)
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        xhr.send("id=" + id + "&img=" + img + "&flag=ajax")
      }, () => {
        layer.msg('你取消了')
      });
    }


    // 查看全文
    $("#tbody").on('click','.showContent', function () {
      // alert(1)
      let data = JSON.parse($(this).attr('data-item'))
      let {
        title,
        content,
        author
      } = data;
      // 组装内容
      let htmlStr = `
        <div style="padding:10px;">
          <h2 style='text-align:center'>${title}</h2>
          <h2 style='text-align:center'>作者： ${author}</h2> 
          <p>${content}</p><div>`;
      layer.open({
        type: 1,
        shadeClose: true,
        area: ['820px', '540px'], //宽高
        content: htmlStr
      });
    })


  //搜索功能
    $('#btn').on('click',function(){
      title = $('#title').val();
      if(!title){
        layer.msg('条件不能为空')
        return
      }

      btn = $('#btn').val();
      isSearch = true;//点击按键
      GetPagingData(curr,limit, function(res){
        //获取分页数据
        let{count,data} = res;
        RenderPagingStructure(laypage,'paging',count,limit)
        //渲染分页结构
        isSearch = false;
        let result = RenderingTableData(data)
        console.log(result);
        //表格数据拼接(RenderingTableData)
        $("#tbody").html(result);
      },{title,Audit_status})
    })
  </script>
</body>

</html>